package com.run.bcpimp.extract;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.jdom2.Element;

import com.run.bcpimp.conf.DbFieldConfig;
import com.run.bcpimp.exception.BcpConfigurationException;
import com.run.bcpimp.processor.BcpRecordContext;
import com.run.bcpimp.util.BcpUtils;

/**
 * 
 * @author chenxu
 *
 */
public class SubstringSetter extends FieldsSetter {
	
	public String dbfieldName;
	/**
	 * 使用 {@link Calendar}中的各种标示来标示，日周月，详见
	 * 下面的 {@link #setFields(BcpRecordContext)}方法的实现
	 */
	public int calendarFlag;
	public int dbIndex;
	public boolean isNull;
	public int length;
	private List<Field> fieldsList;
	
	private static class Field {
		public int bcpIndex;
		public int dbIndex;
		public int length;
		
		public int beginIndex;
		public int endIndex;
		
		public boolean isNULL;
	}

	@Override
	public boolean init(Element setterEle) throws BcpConfigurationException {
		Map<String, DbFieldConfig> dbFieldsMap = cfg.getDbTableConfig().getDbFieldsMap();
		
		fieldsList = new ArrayList<Field>();
		
		if(null!=setterEle) {

			List<Element> items = setterEle.getChildren("item");
			for(Element itemEle : items) {
				String dbFieldName = itemEle.getAttributeValue("dbFieldName");
				String bcpFieldName = itemEle.getAttributeValue("bcpFieldName");
				int beginIndex = Integer.parseInt(itemEle.getAttributeValue("beginIndex", "0")) ;
				int endIndex = Integer.parseInt(itemEle.getAttributeValue("endIndex")) ;
				DbFieldConfig dbFieldConfig = dbFieldsMap.get(dbFieldName);
				if(null==dbFieldConfig) {
					throw new BcpConfigurationException("SubstringSetter dbFieldName["+dbFieldName+"]'s db field config not exists, id["+cfg.getId()+"], table["+cfg.getDbTableConfig().table+"] , dbFieldsMap:"+dbFieldsMap);
				}
				
				Field field = new Field();
				field.dbIndex = 	dbFieldConfig.colIndex;
				field.bcpIndex = bc.getColumnConfig(bcpFieldName).colIndex;
				field.beginIndex = beginIndex;
				field.endIndex = endIndex;
				field.length = dbFieldConfig.len;
				field.isNULL = dbFieldConfig.isNull;
				fieldsList.add(field);
			}
			
					
		} else {
			return false;
		}
		
		return true;
	}

	@Override
	public boolean setFields(BcpRecordContext bcp) throws IOException,
			InterruptedException {
			
		for(Field field : fieldsList) {
			int len = bcp.colPosLens[field.bcpIndex];
			if(len<=0) {
				if(field.isNULL) {
					colValues[field.dbIndex] = null;
				} else {
					return true;
				}
			} /*else 	if(len>field.length) {
				bc.getContext().getCounter(BcpUtils.MR_COUNTER_GROUP, "filter.len.exceed").increment(1);
			}*/ else {
				String str = new String(bcp.buf,bcp.colPosOffsets[field.bcpIndex],len,BcpUtils.CHARSET_UTF8);
				colValues[field.dbIndex] = str.substring(field.beginIndex, field.endIndex);
			}
		}

		return false;
	}
	

}
